#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022, Andrey Kunitsyn
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

class Instance(Module):
    def __init__(self, driver, instance):
        self.instance = int(instance)
        self.driver = driver

    def init(self, module):
        module.name = str(self.instance)
        module.description = "Instance {}".format(self.instance)

    def prepare(self, module, options):
        return True

    def build(self, env):
        env.substitutions = {
            "id": self.instance,
            "use_fiber": env.get(":processing:protothread:use_fiber", True)
        }
        env.outbasepath = "modm/src/modm/platform/spi"

        env.template("spi_master.hpp.in", "spi_master_{}.hpp".format(self.instance))
        env.template("spi_master.cpp.in", "spi_master_{}.cpp".format(self.instance))

        if env.has_module(":platform:dma"):
            env.template("spi_master_dma.hpp.in", "spi_master_{}_dma.hpp".format(self.instance))
            env.template("spi_master_dma_impl.hpp.in", "spi_master_{}_dma_impl.hpp".format(self.instance))


def init(module):
    module.name = ":platform:spi"
    module.description = "Serial Peripheral Interface (SPI)"

def prepare(module, options):
    device = options[":target"]
    if not device.has_driver("spi:rp20*"):
        return False

    module.depends(
        ":architecture:spi",
        ":architecture:assert",
        ":cmsis:device",
        ":math:algorithm",
        ":platform:gpio",
        ":platform:clockgen")

    for driver in device.get_all_drivers("spi:rp20*"):
        for instance in driver["instance"]:
            module.add_submodule(Instance(driver, instance))

    return True

def build(env):
    pass
